import socket
import sys

def usageAndQuit():
	print "USAGE: python server.py PORTNUMBER"
	print "	  PORTNUMBER = { 1024, 1025, ..., 65534, 65535 }"
	quit()


HOST = '127.0.0.1'
totalCount = 0
try:
	if len( sys.argv ) < 2:
		usageAndQuit()
	PORT = int( sys.argv[1] )
	if PORT < 1024 or PORT > 65535:
		usageAndQuit()
except:
	usageAndQuit()

s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
s.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
s.bind( ( HOST, PORT ) )
s.listen( 10 )

try:
	while 1:
		conn, addr = s.accept()
		print 'Connected by', addr
		flag = False
		while 1:
			data = conn.recv( 1024 )
			if not data:
				break
			conn.sendall( data )
			flag = True
		conn.close()
		if flag:
			totalCount += 1
except KeyboardInterrupt:
	s.close()
	print "Served %d clients" % totalCount
